#include "press_move_release_widget.h"

#include "labelx.h"

#include <QLabel>
#include <QVBoxLayout>
#include <QEvent>
#include <QMouseEvent>
#include <QDebug>

PressMoveReleaseWidget::PressMoveReleaseWidget(QWidget *parent): QWidget{parent}
{
    // 垂直布局
    QVBoxLayout* verticalLayout = new QVBoxLayout(this);

    // 文本
    LabelX* labelx = new LabelX(this);
    labelx->setText("");
    labelx->setFrameShape(QFrame::Box);
    labelx->setFixedHeight(50);
    labelx->setAlignment(Qt::AlignCenter);
    labelx->setStyleSheet("background-color: blue; color: white; font-size: 25px");

    verticalLayout->addWidget(labelx);

    // 添加个标准的Label
    widget = new QWidget(this);
    label = new QLabel(widget);
    label->setText("");
    label->setFrameShape(QFrame::Box);
    label->setFixedSize(50, 50);
    label->setStyleSheet("background-color: red;");

    verticalLayout->addWidget(label);

    // 安装事件过滤器
    label->installEventFilter(this);

}

bool PressMoveReleaseWidget::eventFilter(QObject *watched, QEvent *event)
{
    if(watched != label)
    {
        return QWidget::eventFilter(watched, event);
    }

    // 按下
    if(event->type() == QEvent::MouseButtonPress)
    {
        label->setStyleSheet("background-color: green;");

        QMouseEvent* mouseEvent = static_cast<QMouseEvent*>(event);
        pressPos = mouseEvent->globalPos(); // 获取鼠标按下的全局位置(全局坐标，屏幕)
        windowPos = label->pos(); // label的位置(局部坐标，相对于父控件)

        qDebug() << "鼠标按下的位置：" << pressPos;
        qDebug() << "Label的位置：" <<windowPos;
    }
    else if(event->type() == QEvent::MouseMove){ // 鼠标移动
        QMouseEvent* mouseEvent = static_cast<QMouseEvent*>(event);
        QPoint dstPos = mouseEvent->globalPos() - pressPos + windowPos;
        label->move(dstPos);

        // 超过了左边界
        if(label->pos().x() < 0) {
            label->move(0, dstPos.y());
        }

        // 超过了右边界
        if(label->pos().x() > widget->width() - label->width()) {
            label->move(widget->width() - label->width(), dstPos.y());
        }

        // 超过了最上面
        if(label->pos().y() < 0) {
            label->move(dstPos.x(), 0);
        }

        // 超过了最下面
        if(label->pos().y() > widget->height() - label->height()) {
            label->move(dstPos.x(), widget->height() - label->height());
        }
    }
    else if(event->type() == QEvent::MouseButtonRelease) {
        label->setStyleSheet("background-color: red;");
    }

}
